package com.nsccjn.aoh.eslog.controller;

import io.netty.util.internal.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@Api(value = "ESlog接口", tags = {"获取ESlog信息接口"})
@RestController
public class ESLogController {

    @Autowired
    private ElasticsearchRestTemplate template;

    @Value("${pojo.path}")
    String POJO_PATH;

    @GetMapping("/hel")
    public String hello() {
        return "李清照";
    }

    /**
     * 获取elasticsearch中的日志
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param index     索引
     * @param key       关键字
     * @param fieldName 关键字对应的要查询的字段
     * @param page      当前页
     * @param size      一页显示多少条数据
     */
    @ApiOperation(value = "查询ESlog信息", notes = "查询ESlog信息", httpMethod = "GET", produces = "multipart/form-data")
    @GetMapping("/queryESlog")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "startTime", value = "开始时间", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "结束时间", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "index", value = "索引名称", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "key", value = "关键字", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "fieldName", value = "要查询的字段名称", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "当前页", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "size", value = "一页显示多少条数据", dataType = "Integer", paramType = "query")
    })
    public Object queryESlog(String startTime,
                             String endTime,
                             String index,
                             String key,
                             String fieldName,
                             Integer page,
                             Integer size) {

        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        // 查询字段是fieldName，值是’key‘的数据
        if (!StringUtil.isNullOrEmpty(key) && !StringUtil.isNullOrEmpty(fieldName)) {
            queryBuilder.must(QueryBuilders.matchQuery(fieldName, key));
        }
        // 时间范围查询
        if (!StringUtil.isNullOrEmpty(startTime) && !StringUtil.isNullOrEmpty(endTime)) {
            queryBuilder.must(QueryBuilders.rangeQuery("@timestamp").gte(startTime).lte(endTime));
        }

        // 创建NativeSearchQueryBuilder
        NativeSearchQueryBuilder query = new NativeSearchQueryBuilder();
        query.withQuery(queryBuilder);
        // 分页查询
        if (page != null && size != null) {
            Pageable pageable = PageRequest.of(page, size);
            query.withPageable(pageable);
        }
        // 默认按照id倒序排序
        query.withSort(SortBuilders.fieldSort("id").order(SortOrder.DESC));
        // query.withSort(SortBuilders.fieldSort("@timestamp").order(SortOrder.DESC));

        try {
            // 通过反射的方式获取类对象
            Class clazz = Class.forName(POJO_PATH + index);
            // 查询
            SearchHits<Object> search = template.search(query.build(), clazz);
            // search.getSearchHits().forEach(System.out::println);
            return search;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        return null;
    }


}
